package test06thread;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author xhw
 * @Date 2023/10/19
 * @Version 1.0
 */

//利用多线程展示一分钟动态时钟的效果
public class Clock {
    public static void main(String[] args) {
        //创建两个线程，传入不同的参数
        Thread thread1 = new Thread(new ClockThread("时钟1", 60));
        Thread thread2 = new Thread(new ClockThread("时钟2", 60));

        //线程启动
        thread1.start();
        thread2.start();
    }

    //定义一个内部类作为实体类
    static class ClockThread implements Runnable {
        //定义线程名称
        private String threadName;
        //定义打印次数
        private int number;

        //构造函数，接受两个参数
        public ClockThread(String threadName, int number) {
            this.threadName = threadName;
            this.number = number;
        }

        //线程的输出时间方法，每次循环打印当前时间，并且暂停一秒实现每秒输出一次
        @Override
        public void run() {
            //使用DateTimeFormatter初始化时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < number; i++) {
                LocalDateTime now = LocalDateTime.now();
                String time = now.format(formatter);
                System.out.println(threadName + " 正在显示现在时间: " + time);

                try {
                    // 暂停1秒钟
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }
}
